import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

// 引入各个页面
import home from '@/views/home/home.vue'
import category from '@/views/category/category'
import shopcart from '@/views/shopcart/shopcart'
import user from '@/views/user/user'
import productList from '@/views/product-list/product-list'
import productDetail from '@/views/product-detail/product-detail'
import login from '@/views/login/login'
import register from '@/views/register/register'
import profile from '@/views/profile/profile'
import proxy from '@/views/login/proxy'
// 传递参数形式
// 第一种
//this.$router.push({ path: '/product/', query: { id: item.id }, component: productDetail, meta: { index: 3 } }),
// 第二种
//this.$router.push({ path: '/product/', params: { id:item.id }, component: productDetail, meta: { index: 3 } }),
// 第三种
// { path: '/product?id'+item.id, component: productDetail, meta: { index: 3 } },
//第四种（下面）

// 配置相关路由
const routes = [
    // meta（路由守卫）可以在路由导航守卫跳转的时候判断有没有这个信息,如果有让跳转
    { path: '/', redirect: '/home', meta: { index: 1 } },
    { path: '/home', component: home, meta: { index: 1 } },
    { path: '/category', component: category, meta: { index: 1 } },
    { path: '/shopcart', component: shopcart, meta: { index: 1, auth: true } },
    { path: '/user', component: user, meta: { index: 1, auth: true } },
    { path: '/product-list', component: productList, meta: { index: 2 } },
    // 需要传递参数ID （第四种）
    { path: '/product/:id', component: productDetail, meta: { index: 3 } },
    { path: '/login', component: login, meta: { index: 2 } },
    { path: '/register', component: register, meta: { index: 3 } },
    { path: '/profile', component: profile, meta: { index: 2 } },
    { path: '/proxy', component: proxy, meta: { index: 2 } },
]

const router = new VueRouter({
    mode: "history",
    routes
})
import store from '@/store/index';
import { Toast } from 'vant';
//全局前置守卫
router.beforeEach((to, from, next) => {
    // 需要验证的路由
    if (to.meta.auth) {
        // 获取用户登录信息
        const userinfo = store.state.userinfo
        if (userinfo && userinfo.username != undefined) {
            next()
        } else {
            Toast('请先登录')
            next('/login')
        }
    } else {
        // 不需要验证的路由
        next()
    }
})
export default router